package com.jiandian.service.impl;

import com.jiandian.component.IdWoker;
import com.jiandian.crudparams.PageInfo;
import com.jiandian.dao.SysLogMapper;
import com.jiandian.entity.SysLog;
import com.jiandian.service.SysLogService;
import com.jiandian.util.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

/**
 * 系统日志
 *
 * @author lik
 * @date 2018/10/26
 */
@Service
public class SysLogServiceImpl implements SysLogService {

    private static final Logger logger = LoggerFactory.getLogger(SysLogServiceImpl.class);

    @Autowired
    private SysLogMapper mapper;
    @Autowired
    private IdWoker idWoker;

    @Override
    public SysLog add(SysLog record) {

        initBasicValue(record);

        int result = mapper.insert(record);
        if (result > 0) {
            return record;
        }
        return null;
    }

    @Override
    public SysLog update(SysLog record) {
        Integer id = record.getId();
        if (id == null) {
            return null;
        }
        SysLog dbSysLog = mapper.selectByPrimaryKey(id);
        if (dbSysLog == null) {
            return null;
        }
        BeanUtils.copyProperties(record, dbSysLog);
        dbSysLog.setGmtModified(new Timestamp(System.currentTimeMillis()));
        int result = mapper.updateByPrimaryKey(dbSysLog);
        if (result > 0){
            return dbSysLog;
        }
        return null;
    }

    @Override
    public SysLog findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SysLog> findAll(PageInfo pageInfo) {
        return mapper.selectAll(pageInfo);
    }

    @Override
    public int selectCount(PageInfo pageInfo) {
        return mapper.selectCount(pageInfo);
    }

    @Override
    public int batchInsert(List<SysLog> list) {
        for (SysLog bean : list) {
            initBasicValue(bean);
        }
        return mapper.batchInsert(list);
    }

    @Override
    public List<SysLog> batchQueryByIds(List<Integer> ids) {
        return mapper.batchQueryByIds(ids);
    }

    @Override
    public int delete(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int delete(SysLog record) {
        return delete(record.getId());
    }

    @Override
    public int batchDeleteById(List<Integer> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            return mapper.batchDeleteById(ids);
        }
        return 0;
    }

    private void initBasicValue(SysLog record){
        Timestamp now = new Timestamp(System.currentTimeMillis());
        record.setGmtCreate(now);
        record.setGmtModified(now);
    }
}
